package com.twenty.seven.toolbox.encrypt.symmetry;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @Author 001
 * @Date 2020/1/7 10:37
 * @TODO 3DES算法对称加密和解密，可以key值要自己定
 **/
public class TripDESUtil {

    private static final String KEY_ALGORITHM = "DESede";
    /**3DES默认的加密算法**/
    private static final String DEFAULT_CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";

    /**
     * DESede加密
     * @param content 加密内容
     * @param key 密钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String key) throws Exception{
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        byte[] byteContent = content.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE,getSecretKey(key));
        byte[] result = cipher.doFinal(byteContent);
        return Base64.encodeBase64String(result);
    }

    /**
     * DESede解密
     * @param content 解密内容
     * @param key 密钥
     * @return
     */
    public static String decrypt(String content,String key) throws Exception{
        Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE,getSecretKey(key));
        byte[] result = cipher.doFinal(Base64.decodeBase64(content));
        return new String(result,"utf-8");
    }
    /**
     * 生成加密密钥
     * @param key
     * @return
     */
    private static SecretKeySpec getSecretKey(final String key) throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        keyGenerator.init(new SecureRandom(key.getBytes()));
        SecretKey secretKey = keyGenerator.generateKey();
        return new SecretKeySpec(secretKey.getEncoded(),KEY_ALGORITHM);
    }

    public static void main(String[] args) throws Exception{
        String content = "wangzhq,您好!";
        String key = "mgQt5lsxFb5GPQA==";
        System.out.println("Content:"+content);
        String s1 = TripDESUtil.encrypt(content,key);
        System.out.println("S1:"+s1);
        System.out.println("S2;"+TripDESUtil.decrypt(s1,key));
    }

}
